package com.example.yang.yixin.Service;

import android.animation.ObjectAnimator;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.yang.yixin.Activity.PhoneControlActivity;
import com.example.yang.yixin.R;
import com.example.yang.yixin.Socket.Signset;
import com.example.yang.yixin.Utils.DimensionUtils;
import com.example.yang.yixin.Utils.ScreenLock;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.android.volley.VolleyLog.TAG;

public class RefreshService extends Service {
    Timer timer;
    Timer timer1;
    private ScreenLockReceiver receiver;
    private ScreenLock screenLock;
    private SharedPreferences pref;
    private TimerTask timerTask;
    private int timeCount;
    private int timeCountMax;
    private Intent countIntent;
    private Intent maxIntent;
    private ObjectAnimator downAnimation;//11
    private ObjectAnimator upAnimation;//11
    View view;
    List list = new ArrayList();

    public RefreshService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        timer=new Timer();
        timer1=new Timer();
        pref = getSharedPreferences("user", MODE_PRIVATE);
        System.out.println(pref.getString("identity",""));
        countIntent = new Intent("com.brilliantbear.putdownthephone.COUNT");//目前的进度
        maxIntent = new Intent("com.brilliantbear.putdownthephone.COUNT_MAX");//最大值
        timeCountMax = 2*60;
        timeCount = timeCountMax;
        maxIntent.putExtra("count_max", timeCountMax);

       screenLock=new ScreenLock(this);
        maxIntent.putExtra("count_max", timeCountMax);

        sendBroadcast(maxIntent);

        downAnimation = ObjectAnimator.ofFloat(null, "translationY", 0, DimensionUtils.dp2px(getResources(), 120));
        downAnimation.setDuration(500);
        upAnimation = ObjectAnimator.ofFloat(null, "translationY", DimensionUtils.dp2px(getResources(), 120), 0);
        upAnimation.setDuration(500);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startimer();
        return super.onStartCommand(intent, flags, startId);
    }
    Handler handler = new Handler()
    {
        @RequiresApi(api = Build.VERSION_CODES.O)
        public void handleMessage(Message msg)
        {
            switch(msg.what)
            {
                case 0:

                    checkMode(0);

                      if(pref.getString("identity","").equals("学生")){
                          receiver = new ScreenLockReceiver();
                          IntentFilter filter = new IntentFilter();
                          filter.addAction(Intent.ACTION_SCREEN_ON);
                          registerReceiver(receiver, filter);

                      }
                    StartTimer();

                break;

            }

        }
    };
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }

    }
    private void stopTimer() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }
    private void StartTimer() {

        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    timeCount--;

                    countIntent.putExtra("count", timeCount);
                    sendBroadcast(countIntent);

                    if (timeCount <= 0) {
                        Intent intent = new Intent("com.brilliantbear.putdownthephone.TIME_UP");
                        sendBroadcast(intent);
                        stopTimer();
                        stopSelf();

                    }
                }
            };
        }
        timer1.schedule(timerTask, 0, 500);

    }

    private void  startimer() {
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                final String bkpassword=pref.getString("bkpassword","");
                final  String username=pref.getString("username","");
                String jsonurl = "http://47.106.141.161/MyFirstAndroidApp/ControlSignServlet?bkpassword=" + bkpassword;
                RequestQueue mQueue = Volley.newRequestQueue(RefreshService.this);
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {

                            String ss = response.getString("tf");
                            if (ss.equals("true")) {
                                Message ms = new Message();
                                ms.what = 0;
                                handler.sendMessage(ms);
                                timer.cancel();
                                Signset.ChangeControl(bkpassword,username,RefreshService.this,view);


                                Log.d("状态","停止搜索");


                            }
                            Log.d("状态","搜索ing");

                        } catch (JSONException e) {

                            Log.e("json错误", e.getMessage());
                        }
                    }
                },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Log.e("TAG错误", volleyError.getMessage(), volleyError);
                            }
                        }) {
                    protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                        try {
                            JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                            return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                        } catch (JSONException je) {
                            return Response.error(new ParseError(je));
                        } catch (UnsupportedEncodingException e) {
                            return Response.error(new ParseError(e));
                        }

                    }
                };


                mQueue.add(jsonObjectRequest);


            }


        }, 2000, 10000);


    }
    private boolean checkMode(int mode) {
        boolean result = false;
        if(mode == 0){
            if (screenLock.isActive()) {
                screenLock.lock();
                result = true;
            }
        }
        return result;
    }
    class ScreenLockReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            screenLock.lock();
            Log.d(TAG, "receive");
        }
    }

}
